package com.kelvin.backend.common.web.response;

import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.kelvin.backend.common.util.date.DatePattern;

import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * <p>Title: Response</p>
 * <p>Description: 返回结果实体</p>
 *
 * @author Kelvin.Chen
 * @datetime 2021/7/8 15:26
 */
public class BaseResponse<T> implements Serializable {

    /**
     * 返回代码
     */
    private String code;

    /**
     * 返回消息
     */
    private String msg;

    /**
     * 返回数据
     */
    private T data;

    /**
     * 返回结果时间
     */
    @JsonFormat(pattern = DatePattern.NORMAL_TIME_MS_PATTERN)
    private LocalDateTime time;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public LocalDateTime getTime() {
        return time;
    }

    public void setTime(LocalDateTime time) {
        this.time = time;
    }

    public BaseResponse() {
        this.code = BaseCode.SUCCESS.code();
        this.msg = BaseCode.SUCCESS.msg();
        this.time = LocalDateTime.now();
    }

    public BaseResponse(T data) {
        this();
        this.data = data;
    }

    public BaseResponse(CodeMsg<String> codeMsg, String msg) {
        this.code = codeMsg.code();
        this.msg = ObjectUtil.isEmpty(msg) ? codeMsg.msg() : msg;
        this.time = LocalDateTime.now();
    }

    public static <T> BaseResponse<T> response(CodeMsg codeMsg, String msg, T data) {
        BaseResponse response = new BaseResponse(codeMsg, msg);
        response.setData(data);
        return response;
    }

    public static <T> BaseResponse<T> response(CodeMsg codeMsg) {
        BaseResponse response = new BaseResponse(codeMsg);
        return response;
    }

    public static BaseResponse success() {
        return new BaseResponse();
    }

    public static <T> BaseResponse<T> success(T data) {
        return new BaseResponse<>(data);
    }

    public static BaseResponse fail(String msg) {
        return new BaseResponse<>(BaseCode.FAIL, msg);
    }

    public static BaseResponse fail(CodeMsg codeMsg, String msg) {
        return new BaseResponse(codeMsg, msg);
    }

    public static BaseResponse response(String code, String msg) {
        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setCode(code);
        baseResponse.setMsg(msg);
        return baseResponse;
    }

    @Override
    public String toString() {
        return "BaseResponse{" +
                "code='" + code + '\'' +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                ", time=" + time +
                '}';
    }
}
